from django.contrib import admin

from . import models
from celery_tasks.html.tasks import generate_static_list_search_html,generate_static_sku_detail_html

class GoodsCategoryAdmin(admin.ModelAdmin):

    def save_model(self, request, obj, form, change):
        """
       当点击admin编辑界面中的保存按钮时就会来调用此方法
       :param request: 本次保时的请求对象
       :param obj: 要进行保存或修改的模型对象
       :param form: 本次提交表单
       :param change: 是否有修改 True False
       :return: None
       """
        obj.save()
        generate_static_list_search_html.delay() # 触发异步任务生成商品列表静态页面

    def delete_model(self, request, obj):
        """
       当点击admin编辑界面中的删除按钮时会调用此方法
       :param request: 删除操作的请求对象
       :param obj: 要被删除的模型对象
       :return:
       """
        obj.delete()
        generate_static_list_search_html.__delay()


class GoodsChannelAdmin(admin.ModelAdmin):

    def save_model(self, request, obj, form, change):
        """
        当点击admin编辑界面中的保存按钮时就会来调用此方法
        :param request: 本次保时的请求对象
        :param obj: 要进行保存或修改的模型对象
        :param form: 本次提示表单
        :param change: 是否有修改 True False
        :return: None
        """
        obj.save()
        generate_static_list_search_html.delay()  # 触发异步任务生成商品列表静态页面

    def delete_model(self, request, obj):
        """
        当点击admin编辑界面中的删除按钮时会调用此方法
        :param request: 删除操作的请求对象
        :param obj: 要被删除的模型对象
        :return:
        """
        obj.delete()
        generate_static_list_search_html.delay()



class SKUAdmin(admin.ModelAdmin):
    """SKU商品"""
    def save_model(self, request, obj, form, change):
        obj.save()
        generate_static_sku_detail_html.delay(obj.id)



class SKUImageAdmin(admin.ModelAdmin):
    """SKU图片"""

    def save_model(self, request, obj, form, change):
        obj.save()
        # 如果当前sku商品没有默认图片,给它设置一个默认图片
        if obj.sku.default_image_url is None:
            obj.sku.default_image_url = obj
        generate_static_sku_detail_html.delay(obj.sku.id)

    def delete_model(self, request, obj):
        obj.delete()
        generate_static_sku_detail_html.delay(obj.sku.id)




admin.site.register(models.GoodsCategory, GoodsCategoryAdmin)
admin.site.register(models.GoodsChannel, GoodsChannelAdmin)
admin.site.register(models.Goods)
admin.site.register(models.Brand)
admin.site.register(models.GoodsSpecification)
admin.site.register(models.SpecificationOption)
admin.site.register(models.SKU, SKUAdmin)
admin.site.register(models.SKUSpecification)
admin.site.register(models.SKUImage, SKUImageAdmin)